package netcode.server;

import java.net.InetAddress;
import java.util.Map;
import java.util.concurrent.ConcurrentSkipListMap;

public class ConnectedClientFactory {
	private static Map<Integer, ConnectedClient> connectedClients = new ConcurrentSkipListMap<Integer, ConnectedClient>();

	private ConnectedClientFactory() {
	}

	public static Integer generateConnectedClient(InetAddress address,
			int port, String name) {
		ConnectedClient newClient = new ConnectedClient(address, port, name);
		Integer currentKey = new Integer(address.hashCode());
		if (connectedClients.containsValue(newClient)) {
			while (!connectedClients.get(currentKey).equals(newClient)) {
				if (currentKey.equals(Integer.MAX_VALUE)) {
					currentKey = new Integer(Integer.MIN_VALUE);
				} else {
					currentKey = new Integer(currentKey.intValue() + 1);
				}
			}
			return currentKey;
		} else {

			// There is a possibility of infinite looping here. Needs to be
			// fixed.
			while (connectedClients.containsKey(currentKey)) {
				if (currentKey.equals(Integer.MAX_VALUE)) {
					currentKey = new Integer(Integer.MIN_VALUE);
				} else {
					currentKey = new Integer(currentKey.intValue() + 1);
				}
			}
			connectedClients.put(currentKey, newClient);
			return currentKey;
		}
	}

	public static ConnectedClient getConnectedClient(Integer key) {
		return connectedClients.get(key);
	}

	public static void disconnectClient(Integer key) {
		connectedClients.remove(key);
	}
}
